package com.ds.esd.localproxy.handler;

import com.ds.common.JDSConstants;
import com.ds.common.JDSException;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.common.util.StringUtility;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.localproxy.Conts;
import com.ds.esd.project.ProjectCacheManager;
import com.ds.esd.tool.module.EUModule;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.server.httpproxy.handler.SpringMVCHandler;
import com.ds.template.JDSFreemarkerResult;
import com.ds.vfs.FileInfo;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;
import com.ds.vfs.ct.admin.CtAdminVfsServiceImpl;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Map;
import java.util.regex.Pattern;

public class VFSClsHandler extends AbstractRADHandler {
    private static final Log logger = LogFactory.getLog(JDSConstants.CONFIG_KEY, SpringMVCHandler.class);

    Pattern rule;
    CtAdminVfsServiceImpl vfsClient;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    void getMethodBean(String methodName) {

    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {

        boolean ruleMatches = rule.matcher(request.getUrl()).matches();
        if (!ruleMatches) {
            return false;
        }
        String path = request.getPath();

        if (path.indexOf("?") > -1) {
            path = path.substring(0, path.indexOf("?"));
        }

        if (path.indexOf("#") > -1) {
            path = path.substring(0, path.indexOf("#"));
        }


        logger.info("httpUrl=" + path);
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        for (String ckey : CKEY) {
            String key = ckey + "/";
            if (path.startsWith(key)) {
                path = path.substring(key.length());
            }
        }


        String projectName = this.getProjectName(request);
        path = this.formatPath(request.getUrl(), projectName);
        // 激活下载操作
        InputStream stream = null;
        FileInfo fileInfo = null;
        try {

            try {
                fileInfo = ESDFacrory.getESDClient().getFileByPath(path, projectName);
            } catch (JDSException e) {
                e.printStackTrace();
            }


            path = StringUtility.replace(path, ".js", ".cls");
            if (fileInfo == null) {
                try {
                    fileInfo = ESDFacrory.getESDClient().getFileByPath(path, projectName);
                } catch (JDSException e) {
                    e.printStackTrace();
                }
            }

            if (fileInfo == null) {
                try {
                    fileInfo = getVfsClient().getFileByPath(path);
                } catch (JDSException e) {
                    e.printStackTrace();
                }
            }

            if (fileInfo == null) {
                path = StringUtility.replace(path, ".cls", ".js");
                fileInfo = getVfsClient().getFileByPath(path);
            }


        } catch (JDSException e) {
            e.printStackTrace();
        }

        if (fileInfo != null && fileInfo.getPath().endsWith(".cls")) {

            try {
                EUModule module = ProjectCacheManager.getInstance(ESDFacrory.getESDClient().getSpace()).loadEUClass(fileInfo.getPath(), projectName, true);
                if (module != null) {
                    Map allParamsMap = this.getAllParamMap(null, request);
                    module.getComponent().fillFormValues(allParamsMap, false);
                    String mimeType = "application/javascript";
                    String json = ESDFacrory.getESDClient().genJSON(module, null).toString();
                    response.sendResponse(json, mimeType + ";");
                    return true;
                } else {
                    return false;
                }
            } catch (JDSException e) {
                e.printStackTrace();
            }
        }


        if (fileInfo != null) {
            stream = fileInfo.getCurrentVersonInputStream();
        }

        if (stream != null) {
            String mimeType = Conts.getSuffixMap().get(fileInfo.getName().substring(fileInfo.getName().indexOf(".")));
            response.setMimeType(mimeType);
            response.addHeader("Content-disposition", "filename=" + new String(fileInfo.getName().getBytes("utf-8"), "ISO8859-1"));
            JDSFreemarkerResult freemarkerResult = new JDSFreemarkerResult();
            if (fileInfo.getPath().endsWith(".js")) {
                try {
                    Writer stringWriter = freemarkerResult.doExecute(fileInfo.getCurrentVersonFileHash(), CtVfsFactory.getLocalCachePath());
                    response.setMimeType(mimeType);
                    String json = stringWriter.toString();
                    response.sendResponse(getInputStream(json, "utf-8"), -1);

                } catch (TemplateException e) {
                    e.printStackTrace();
                }
            } else {
                response.addHeader("Content-Length", String.valueOf(fileInfo.getCurrentVersion().getLength()));
                response.sendResponse(stream, fileInfo.getCurrentVersion().getLength().intValue());

            }
        }

        return true;
    }


    public CtVfsService getVfsClient() {
        if (vfsClient == null) {
            this.vfsClient = new CtAdminVfsServiceImpl();
        }
        return vfsClient;
    }

}
